var OrderProgressBoard = function () {
  var SearchForm = function () {
    var template = /* html */ `
      <el-form class="order-progress-search-form" label-width="73px" size="small">
        <el-form-item label="部门-车间" v-if="search.orderId===''">
          <el-cascader clearable filterable v-model="search.deptWork" :options="deptWorkList" placeholder="请选择部门-车间" separator="-"
            :props="deptWorkProps" class="search-input"></el-cascader>
        </el-form-item>
        <el-form-item label="设备编号">
          <page-select clearable filterable class="search-input" v-model="search.equipmentNo" :options="equipmentNoList"
            placeholder="请选择设备编号"></page-select>
        </el-form-item>
        <el-form-item label="订单编号">
          <page-select clearable filterable class="search-input" v-model="search.orderId" :options="orderIdList" placeholder="请选择订单编号"
            :filter-method="orderFilterMethod">
            <template slot-scope="scope">
              <el-option v-for="order in scope.options" :key="order.orderId" :value="order.orderId" :label="order.orderId">
                <div style="display:flex">
                  <div style="min-width:145px">{{order.orderId}}</div>
                  <div style="min-width:145px">{{order.companyOrderId}}</div>
                  <div style="min-width:110px">{{order.factoryId}}</div>
                  <div style="min-width:50px">{{order.coustomId}}</div>
                </div>
              </el-option>
            </template>
          </page-select>
        </el-form-item>
        <el-form-item label="作业员">
          <page-select clearable filterable class="search-input" v-model="search.createUser" :options="userIdList" placeholder="请选择作业员"
            value-field="createUser" label-field="userName">
          </page-select>
        </el-form-item>
      </el-form>
    `;

    return {
      props: {
        search: {
          type: Object,
          required: true
        },
        deptWorkList: {
          type: Array,
          default: function () {
            return [];
          }
        },
        progressList: {
          type: Array,
          default: function () {
            return [];
          }
        }
      },

      watch: {
        progressList: function () {
          this.equipmentList = null;
          this.orderList = null;
          this.userList = null;
          this.initData();
        },
        changeData: function (newObj, oldObj) {
          if (newObj.equipmentNo !== oldObj.equipmentNo) {
            this.orderList = null;
            this.userList = null;
          }
          if (newObj.orderId !== oldObj.orderId) {
            this.equipmentList = null;
            this.userList = null;
          }
          if (newObj.userId !== oldObj.userId) {
            this.equipmentList = null;
            this.orderList = null;
          }
          this.initData();
        }
      },

      computed: {
        changeData: function () {
          var search = this.search;
          return {
            equipmentNo: search.equipmentNo,
            orderId: search.orderId,
            userId: search.createUser
          };
        },
        equipmentNoList: function () {
          var equipmentList = this.equipmentList;
          if (equipmentList === null) {
            return [];
          }
          return equipmentList;
        },
        orderIdList: function () {
          var orderList = this.orderList;
          if (orderList === null) {
            return [];
          }
          return orderList;
        },
        userIdList: function () {
          var userList = this.userList;
          if (userList === null) {
            return [];
          }
          return userList;
        }
      },

      data: function () {
        return {
          orderList: null,
          equipmentList: null,
          userList: null,
          filterParams: ['orderId', 'companyOrderId', 'factoryId', 'customerId'],
          deptWorkProps: {
            value: 'id',
            label: 'name'
          }
        };
      },

      created: function () {
        this.initData();
      },

      methods: {
        initData: function () {
          this.setEquipmentList();
          this.setOrderList();
          this.setUserList();
        },

        setEquipmentList: function () {
          if (this.equipmentList !== null) {
            return;
          }

          var equipmentList = this.getFilterProgressList('equipmentNo');
          equipmentList = _.map(equipmentList, 'equipmentNo');
          equipmentList = _.uniq(equipmentList);
          this.equipmentList = equipmentList;
        },

        setOrderList: function () {
          if (this.orderList !== null) {
            return;
          }

          var orderList = this.getFilterProgressList('orderId');
          orderList = _.uniqBy(orderList, 'orderId');
          this.orderList = orderList;
        },

        setUserList: function () {
          if (this.userList !== null) {
            return;
          }

          var userList = this.getFilterProgressList('userId');
          userList = _.uniqBy(userList, 'createUser');
          this.userList = userList;
        },

        getFilterProgressList: function (field) {
          var progressList = this.progressList;
          if (SysUtil.isEmpty(progressList)) {
            return [];
          }

          var filterField = [];
          switch (field) {
            case 'equipmentNo':
              filterField = ['orderId', 'createUser'];
              break;
            case 'orderId':
              filterField = ['equipmentNo', 'createUser'];
              break;
            case 'userId':
              filterField = ['orderId', 'equipmentNo'];
              break;
          }

          var search = this.search;
          var filterObj = {};
          for (var i = 0; i < filterField.length; i++) {
            var fieldValue = filterField[i];
            var value = search[fieldValue];
            if (value === '') {
              continue;
            }
            filterObj[fieldValue] = value;
          }

          if (SysUtil.isEmptyObjct(filterObj)) {
            return progressList;
          }
          progressList = _.filter(progressList, filterObj);
          return progressList;
        },

        orderFilterMethod: function (options, queryValue) {
          if (queryValue === '') {
            return options;
          }

          queryValue = queryValue.toLowerCase();
          var filterParams = this.filterParams;
          options = _.filter(options, function (option) {
            for (var i = 0; i < filterParams.length; i++) {
              var filterParam = filterParams[i];
              var value = _.get(option, filterParam, '');
              if (value === null) {
                value = '';
              }
              if (typeof value === 'string') {
                value = value.toLowerCase();
              }
              if (value.indexOf(queryValue) !== -1) {
                return true;
              }
            }
            return false;
          });
          return options;
        }
      },

      components: {
        PageSelect: PageSelect
      },

      template: template
    };
  }();

  var template = /* html */ `
    <div class="order-progress-board" v-loading.fullscreen.lock="loading">
      <search-btns ref="searchBtns" :has-search="true" search-btn-text="查询" :popover-width="275"
        search-title="查询条件" @after-leave="afterLeave">
        <div style="overflow:auto" slot="search" v-if="deptWorkList!==null&&search.deptWork!==null">
          <search-form :search="search" :dept-work-list="deptWorkList" :progress-list="progressList"></search-form>
          <div style="text-align:center;margin-top:4px">
            <el-button size="small" type="primary" @click="searchData">查询</el-button>
          </div>
        </div>
      </search-btns>

      <div class="order-progress-title">
        <span>订单进度</span>
      </div>

      <template v-if="isShow">
        <div class="order-progress-content" :key="boardKey">
          <order-progress-table ref="progressTable" :orders="orderList" v-if="orderList!==null">
          </order-progress-table>

          <template v-else>
            <div v-if="oldSearch.deptWork.length===0" class="no-data">请选择车间查询订单进度</div>
            <div v-else class="no-data">暂无订单进度数据</div>
          </template>
        </div>
      </template>
    </div>
  `;

  return {
    mixins: [boardRunningMixin],

    data: function () {
      var search = {
        deptWork: [],
        equipmentNo: '',
        orderId: '',
        createUser: ''
      };
      return {
        loading: false,
        isShow: false,
        orderList: null,
        deptWorkList: null,
        progressList: [],
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        user: null,
        boardKey: SysUtil.getId(),
        moment: moment
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      this.initData().then(function () {
        self.loading = false;
        self.isShow = true;
        self.boardRunning();
      }).catch(function () {
        self.loading = false;
        self.isShow = true;
      });
    },

    methods: {
      initData: function () {
        var self = this;
        return Promise.all([
          this.getUser(),
          this.setWorkshopList(),
          this.setProgressList()
        ]).then(function (params) {
          var user = params[0];
          var workshopId = user.workShopId;
          if (SysUtil.isEmpty(workshopId) || workshopId === '0') {
            self.search.deptWork = [];
            self.oldSearch.deptWork = [];
            return self.setOrderList(true);
          }

          var deptWorkObj = params[1];
          var obj = deptWorkObj[workshopId];
          if (obj !== undefined) {
            var deptWork = [obj.pId, workshopId];
            self.search.deptWork = _.cloneDeep(deptWork);
            self.oldSearch.deptWork = _.cloneDeep(deptWork);
          } else {
            self.search.deptWork = [];
            self.oldSearch.deptWork = [];
          }
          return self.setOrderList(true);
        });
      },

      getUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          self.user = user;
          return user;
        });
      },

      setWorkshopList: function () {
        var self = this;
        return ajaxRequest('basicData/getWorkshop').then(function (deptWorks) {
          var deptWorkObj = {};
          for (var i = 0; i < deptWorks.length; i++) {
            var deptWork = deptWorks[i];
            var deptId = `dept_${deptWork.deptId}`;
            var deptName = deptWork.productionLine;
            deptWorkObj[deptId] = {
              id: deptId,
              name: deptName,
              pId: null
            };

            var workshopId = deptWork.id;
            var workshopName = deptWork.workshopName;
            deptWorkObj[workshopId] = {
              id: workshopId,
              name: workshopName,
              pId: deptId
            };
          }

          var deptWorkList = [];
          for (var key in deptWorkObj) {
            var deptWork = deptWorkObj[key];
            var parentId = deptWork.pId;
            if (parentId !== null) {
              var parentObj = deptWorkObj[parentId];
              if (!parentObj) {
                continue;
              }
              if (parentObj.children === undefined) {
                parentObj.children = [];
              }
              parentObj.children.push(deptWork);
            } else {
              deptWorkList.push(deptWork);
            }
          }

          self.deptWorkList = deptWorkList;
          return deptWorkObj;
        });
      },

      setProgressList: function () {
        var self = this;
        return ajaxRequest('materialSelectFilter/getMaterialSelectData', {
          type: 29
        }).then(function (progressList) {
          self.progressList = progressList;
          return progressList;
        });
      },

      afterLeave: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.oldSearch = _.cloneDeep(this.search);
        this.clearTimeoutList();
        if (this.$refs['progressTable']) {
          this.$refs['progressTable'].clearTimeoutList();
        }
        this.loading = true;
        var self = this;
        setTimeout(function () {
          self.setOrderList(true).then(function () {
            self.loading = false;
            self.$refs['searchBtns'].closePopover();
            self.boardKey = SysUtil.getId();
            self.boardRunning();
          }).catch(function () {
            self.loading = false;
          });
        }, 100);
      },

      setOrderList: function (hasAlert) {
        if (hasAlert === undefined) {
          hasAlert = false;
        }

        var search = this.search;
        var deptWork = search.deptWork;
        var workshopId = deptWork[1];
        var orderId = search.orderId;

        var postData = {};
        if (orderId === '') {
          if (!SysUtil.isEmpty(workshopId)) {
            postData.workShop = workshopId;
          }
        } else {
          postData.orderId = orderId;
        }

        var equipmentNo = search.equipmentNo;
        if (!SysUtil.isEmpty(equipmentNo)) {
          postData.equipmentNo = equipmentNo;
        }

        var userId = search.createUser;
        if (!SysUtil.isEmpty(userId)) {
          postData.userId = userId;
        }

        var self = this;
        return ajaxRequest('displayView/getEquipmentChangeOrderRecord', postData, true, hasAlert).then(function (orderList) {
          if (SysUtil.isEmpty(orderList)) {
            self.orderList = null;
            self.equipmentNoList = [];
            return null;
          }

          orderList = _.map(orderList, function (order, index) {
            order = new OrderProgressInfo(order);
            order.rowIndex = index;
            return order;
          });
          self.orderList = orderList;

          var equipmentNoList = _.map(orderList, 'equipmentNo');
          equipmentNoList = _.uniq(equipmentNoList);
          self.equipmentNoList = equipmentNoList;
          return self.setEquipmentStatus();
        });
      },

      setEquipmentStatus: function () {
        var equipmentNoList = this.equipmentNoList;
        if (SysUtil.isEmpty(equipmentNoList)) {
          return Promise.resolve([]);
        }

        var orderList = this.orderList;
        return ajaxRequest('equipment/getDynamicEquipmentBoardData', {
          equipmentNos: JSON.stringify(equipmentNoList)
        }).then(function (machineData) {
          for (var i = 0; i < orderList.length; i++) {
            var order = orderList[i];
            var data = machineData[order.equipmentNo];
            if (data !== undefined) {
              order.setEquipmentStatus(data);
            }
          }
          return orderList;
        });
      },

      boardRunning: function () {
        this.clearTimeoutList();

        this.resetOrderList();
        this.resetEquipmentStatus();
      },

      resetOrderList: function () {
        var self = this;
        var timeout = setTimeout(function () {
          self.clearTimeoutList(1);
          self.setOrderList().then(function () {
            self.resetOrderList();
            self.resetEquipmentStatus();
          }).catch(function () {});
          self.timeoutList[0] = null;
        }, 15 * 60 * 1000);
        this.timeoutList[0] = timeout;
      },

      resetEquipmentStatus: function () {
        var self = this;
        var timeout = setTimeout(function () {
          self.setEquipmentStatus().then(function () {
            self.resetEquipmentStatus();
          }).catch(function () {});
          self.timeoutList[1] = null;
        }, 5000);
        this.timeoutList[1] = timeout;
      }
    },

    components: {
      SearchBtns: SearchBtns,
      SearchForm: SearchForm,
      OrderProgressTable: OrderProgressTable
    },

    template: template
  };
}();
